const log = console.log.bind(console)

const parse = (tokens) => {
    const priority = {
        '*': 3,
        '/': 3,
        '+': 2,
        '-': 2,
        '(': 1,
    }
    let sNumber = []
    let sOperator = []
    const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    const chars = ['+', '-', '*', '/', '(']

    let i = 0
    while (i < tokens.length) {
        const t = tokens[i]
        // 遇到数字，就push到number
        if (t === ')') {
            while (sOperator.length !== 0) {
                const operator = sOperator.pop()
                if (operator === '(') {
                    break
                }
                const right = sNumber.pop()
                const left = sNumber.pop()
                // 遇到右括号后
                const o = {
                    type: 'BinaryExpression',
                    operator: operator,
                    right: right,
                    left: left,
                }
                sNumber.push(o)
                // 左边括号只有遇到）括号才能退
            }
        } else if (numbers.includes(t)) {
            sNumber.push(t)
        } else if (chars.includes(t)) {
            if (t === '(') {
                sOperator.push(t)
            } else if (sOperator.length > 0) {
                // 遇到操作符，就比较优先级
                const top = sOperator[sOperator.length - 1]
                if (priority[t] < priority[top]) {
                    // 栈顶是*，t是+
                    //栈顶优先级大于t，弹出栈顶做运算
                    const pop = sOperator.pop()
                    const o = {
                        type: 'BinaryExpression',
                        operator: pop,
                        right: sNumber.pop(),
                        left: sNumber.pop(),
                    }
                    sNumber.push(o)
                }
                // 1- 当前符号的优先级比top高，直接放进符号栈
                // 2- 如果比top优先级低，则运算完后放入符号栈
                sOperator.push(t)
            } else {
                sOperator.push(t)
            }
        }
        i += 1
    }
    // 只要数字栈不为1，就一直做
    while (sNumber.length > 1) {
        // 取出数字栈2个，符号栈1个，做运算后push进数字栈
        const right = sNumber.pop()
        const left = sNumber.pop()
        const operator = sOperator.pop()
        const o = {
            type: 'BinaryExpression',
            operator: operator,
            right: right,
            left: left,
        }
        sNumber.push(o)
    }
    return sNumber[0]
}

// 处理优先级
const testPriority = () => {
    let t = [1, '*', '(', 2, '-', 3, ')', '+', 4, '/', 5]
    let r = parse(t)
    log('r', r)
}

testPriority()
